/***************************************************************************
 * Copyright 2012-2013 TXT e-solutions SpA
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * This work was performed within the IoT_at_Work Project
 * and partially funded by the European Commission's
 * 7th Framework Programme under the contract ICT-257367.
 *
 * Authors:
 *      Salvatore Piccione (TXT e-solutions SpA)
 *
 * Contributors:
 *        Domenico Rotondi (TXT e-solutions SpA)
 **************************************************************************/
package it.txt.ens.schema.osgi;

import it.txt.ens.schema.factory.ENSRequestFactoryException;
import it.txt.ens.schema.request.factory.ENSAuthorisationRequestFactory;
import it.txt.ens.schema.request.factory.ENSAuthorisationRequestFactoryImpl;

import java.text.MessageFormat;
import java.util.Dictionary;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;

/**
 * @author Salvatore Piccione (TXT e-solutions SpA - salvatore.piccione AT txtgroup.com)
 * @author Domenico Rotondi (TXT e-solutions SpA - domenico.rotondi AT txtgroup.com)
 *
 */
public class ENSAuthorisationRequestFactoryMS implements ManagedService{
    private static final Logger LOGGER = Logger.getLogger(ENSAuthorisationRequestFactoryMS.class.getName());
    private static final ResourceBundle LOG_MESSAGES = 
            ResourceBundle.getBundle("log-messages/" + ENSAuthorisationRequestFactoryMS.class.getSimpleName());
    private ENSAuthorisationRequestFactory factory = null;
    private ServiceRegistration<ENSAuthorisationRequestFactory> registration;
    private final BundleContext context;
    
    public ENSAuthorisationRequestFactoryMS (BundleContext context) {
        this.context = context;
    }

    /* (non-Javadoc)
     * @see org.osgi.service.cm.ManagedService#updated(java.util.Dictionary)
     */
    @Override
    public void updated(Dictionary<String, ?> properties)
            throws ConfigurationException {
        if (LOGGER.isLoggable(Level.FINEST))
            LOGGER.finest("Updating the singleton " + ENSAuthorisationRequestFactoryMS.class.getName() + 
                " Properties container is" + (properties == null ? "" : " not") + " null." +
                " Registration is" + (registration == null ? "" : " not") + " null");
        
        if (properties == null) {
            //this means that the configuration has been deleted or doesn't exist
            if (factory != null) {
                registration.unregister();
                factory = null;
            }
        } else {
            String capabilitySchemasRootPath = (String) properties.get(
                    ENSAuthorisationRequestFactory.SCHEMAS_DIRECTORY_PROP_KEY);
            if (registration == null) {
                try {
                    factory = ENSAuthorisationRequestFactoryImpl.getInstance(capabilitySchemasRootPath );
                    registration = context.registerService(ENSAuthorisationRequestFactory.class, factory, properties);
                    registration.setProperties(properties);
                } catch (ENSRequestFactoryException e) {
                    if (LOGGER.isLoggable(Level.SEVERE)) {
                        LOGGER.log(Level.SEVERE, 
                            MessageFormat.format(LOG_MESSAGES.getString("factoryCreation.exception"),
                                ENSAuthorisationRequestFactoryImpl.class.getName()), e);
                    }
                    throw new ConfigurationException(
                            ENSAuthorisationRequestFactory.SCHEMAS_DIRECTORY_PROP_KEY, e.getMessage());
                }
            } else if (!factory.getSchemasRootPath().equals(capabilitySchemasRootPath)) {
                try {
                    factory = ENSAuthorisationRequestFactoryImpl.getInstance(capabilitySchemasRootPath);
                    registration.unregister();
                    registration = context.registerService(ENSAuthorisationRequestFactory.class, factory, properties);
                    registration.setProperties(properties);
                } catch (ENSRequestFactoryException e) {
                    if (LOGGER.isLoggable(Level.SEVERE)) {
                        LOGGER.log(Level.SEVERE, 
                            MessageFormat.format(LOG_MESSAGES.getString("factoryCreation.exception"),
                                ENSAuthorisationRequestFactoryImpl.class.getName()), e);
                    }
                    throw new ConfigurationException(
                            ENSAuthorisationRequestFactory.SCHEMAS_DIRECTORY_PROP_KEY, e.getMessage());
                }
            }
        }
    }
    
    public void unregister () {
        if (registration != null)
            registration.unregister();
        factory = null;
    }

}
